﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LearnDrawing.Controls
{
    /// <summary>
    /// WithPath.xaml 的交互逻辑
    /// </summary>
    public partial class WithPath : UserControl
    {
        public WithPath()
        {
            InitializeComponent();
        }

        public string DrawingTime
        {
            get { return (string)GetValue(DrawingTimeProperty); }
            set { SetValue(DrawingTimeProperty, value); }
        }

        public static readonly DependencyProperty DrawingTimeProperty =
            DependencyProperty.Register("DrawingTime", typeof(string), typeof(WithPath), new UIPropertyMetadata("", null));



        public WaveData WaveData
        {
            get { return (WaveData)GetValue(WaveDataDataProperty); }
            set { SetValue(WaveDataDataProperty, value); }
        }

        public static readonly DependencyProperty WaveDataDataProperty =
            DependencyProperty.Register("WaveData", typeof(WaveData), typeof(WithPath), new UIPropertyMetadata(null, WaveDataPropertyChanged));

        private static void WaveDataPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs arg)
        {
            WithPath? control = obj as WithPath;
            WaveData Data = (WaveData)arg.NewValue;

            if (Data != null)
            {
                Stopwatch stopwatch = new();
                stopwatch.Start();
                control?.DrawWave(Data);
                stopwatch.Stop();
                control.DrawingTime = $"Using: {stopwatch.ElapsedMilliseconds}ms";
            }
        }

        private void DrawWave(WaveData Data)
        {  
            StreamGeometry geometry = new()
            {
                FillRule = FillRule.EvenOdd
            };

            using (StreamGeometryContext ctx = geometry.Open())
            {
                ctx.BeginFigure(new Point(0, 0), true, false);
                for (int i = 0; i < 1900; i++)
                {
                    int x1 = i;
                    int y1 = Data.Datas[i];
                    ctx.LineTo(new Point(x1/2, y1), true, false);                   
                }  
            }
            geometry.Freeze();

            Path pp = new()
            {
                Stroke = new SolidColorBrush(Colors.LightGreen),
                StrokeThickness = 1,
                Data = geometry
            };

            this.MainCanvas.Children.Clear();
            this.MainCanvas.Children.Add(pp);
        }
    }
}
